<template>
  <div>
    <!-- 控制目录图标 -->
    <Icon
      v-show="true"
      @click="clik_showcatalog"
      type="ios-bookmark-outline"
      size="24"
      style="z-index: 3; position: fixed; overflow: auto; right: 3px; top: 35px"
    ></Icon>
    <!-- 触发提交对话框 -->
    <Icon
      size="24"
      @click="modal1 = true"
      type="ios-cloud-upload-outline"
      style="z-index: 3; position: fixed; overflow: auto; right: 3px; top: 65px"
      title="提交文章"
    />
    <div
      :style="'padding-right:' + padding_right + '; display: inline-block'"
      style="width: -webkit-fill-available"
    >
      <!-- 编辑器区域 -->
      <MyEditor></MyEditor>
    </div>
    <!-- 文章目录 -->
    <Sider
      :width="220"
      collapsible
      hide-trigger
      :collapsed-width="0"
      v-model="Collapsed_catalog"
      :style="{
        position: 'fixed',
        height: '100vh',
        right: 0,
        top: '0px',
        overflow: 'auto',
        padding: Sider_padding
      }"
      style="
        z-index: 1;
        background-color: #fff;
        border-right-width: 1px;
        border-color: rgb(220, 222, 226);
        border-style: solid;
      "
    >
      <div>
        <div style="text-align: center">
          <h4 style="text-align: center">本文目录</h4>
          <Icon
            title="切换显示模式"
            :size="24"
            type="ios-analytics-outline"
            @click="
              cata_show_model = cata_show_model == 'normal' ? '' : 'normal'
            "
          />
        </div>
        <p
          :style="'white-space: ' + cata_show_model + ';'"
          :title="item.text"
          v-for="(item, i) in show_title_list"
          :key="i"
          :class="item.type"
          @click="roll_to_title(item.id, $event)"
        >
          {{ item.text }}
        </p>
      </div>
    </Sider>

    <!-- 提交文章对话框 -->
    <Modal v-model="modal1" width="360">
      <template #header>
        <p style="color: #f60; text-align: center">
          <Icon type="ios-information-circle"></Icon>
          <span>请填写文章信息</span>
        </p>
      </template>
      <!-- 内容 -->
      <div style="text-align: center">
        <div>
          <div style="margin-top: 20px">
            <Form :model="formTop" label-position="top">
              <FormItem label="文章标题">
                <Input v-model="formTop.title"></Input>
              </FormItem>
              <FormItem label="文章说明">
                <Input
                  autosize
                  v-model="formTop.explain"
                  type="textarea"
                  placeholder="Enter something..."
                />
              </FormItem>
              <FormItem label="谁可以查看此文章">
                <Select style="width: auto" v-model="formTop.permission">
                  <Option
                    v-for="item in Checkpermissions"
                    :value="item.value"
                    :key="item.value"
                    >{{ item.label }}</Option
                  >
                </Select>
              </FormItem>
              <FormItem label="谁可以查看此文章敏感信息">
                <Select
                  style="width: auto"
                  v-model="formTop.Permission_sensitive"
                >
                  <Option
                    v-for="item in Checkpermissions"
                    :value="item.value"
                    :key="item.value"
                    >{{ item.label }}</Option
                  >
                </Select>
              </FormItem>

              <FormItem label="请选择文件夹">
                <Input v-model="formTop.dir" disabled placeholder=""></Input>
              </FormItem>
            </Form>
            <!-- 选择文件夹 -->
            <Tree
              :data="datadir"
              expand-node
              :render="renderContent"
              class="demo-tree-render"
            >
            </Tree>
          </div>
        </div>
      </div>
      <template #footer>
        <!-- 提交按钮 -->
        <Button @click="submit" type="success" long>提交文章</Button>
      </template>
    </Modal>
    <!-- 未保存信息对话框 -->
    <Modal v-model="modal" width="360">
      <template #header>
        <p style="color: #f60; text-align: center">
          <Icon type="ios-information-circle"></Icon>
          <span>当前存在未保存的文章!</span>
        </p>
      </template>

      <div style="text-align: center">
        <p>请选择操作</p>
      </div>
      <template #footer>
        <div>
          <Button @click="modal = false">取消</Button>
          <Button type="error" @click="edit_articley">不保存</Button>
          <Button type="success" @click="Save_draft_box">保存到草稿箱</Button>
        </div>
      </template>
    </Modal>
  </div>
</template>

<script>
import { resolveComponent } from 'vue'
import putBuffer from '@/api/API_Uploading_Directory_Tree'
import {
  nodeType_article,
  nodeType_root_node,
  nodeType_children_node,
  nodeType_pdf,
  editor_h1,
  editor_h2,
  editor_h3,
  editor_h4,
  editor_h5,
  break_width
} from '@/mylibs/define'
import { getUuid, getNowTime, find_dirNode } from '@/mylibs/functions'
import eventbus from '@/eventBus/eventbus'
// render
import { renderContent } from '@/mylibs/node_render'
import MyEditor from '@/components/MyEditor.vue'
export default {
  name: 'Article_management',
  components: { MyEditor },
  props: {
    // 新建文章模式与编辑文章模式
    // 路由参数
    useModel: {
      required: true,
      type: String
    },
    PATH_Article_editor_data: { required: true, type: String },
    PATH_Directory_tree: { required: true, type: String }
  },
  data() {
    return {
      cata_show_model: '',
      Sider_padding: '0px',
      screenWidth: null,
      padding_right: '180px',
      show_title_list: [],
      Collapsed_catalog: false,
      editorRef: null,
      modal: false,
      modal1: false,
      // 文章权限
      Checkpermissions: [
        {
          value: '仅自己',
          label: '仅自己'
        },
        {
          value: '所有人',
          label: '所有人'
        }
      ],

      formTop: {
        title: '',
        dir: '',
        permission: '仅自己',
        Permission_sensitive: '仅自己',
        // 文章说明信息
        explain: ''
      },
      datadir: [],
      chooseDir_node: null,
      buttonProps: {
        type: 'default',
        size: 'small'
      },

      needEdit_nodeData: null,

      // 文章节点样式
      art_render: (h, { root, node, data }) => {
        return h(
          'span',
          {
            style: {
              display: 'inline-block',
              width: '100%'
            }
          },
          [
            h('span', [
              h(resolveComponent('Icon'), {
                type: 'ios-paper-outline',
                style: {
                  marginRight: '8px'
                }
              }),
              h('span', data.title)
            ])
          ]
        )
      },

      renderContent
    }
  },

  watch: {
    screenWidth(newvar) {
      // 小屏幕
      if (newvar < break_width) {
        this.padding_right = '0px'
        this.Collapsed_catalog = true
      } else {
        this.padding_right = '180px'
      }
    }
  },

  mounted() {
    this.screenWidth = document.body.clientWidth
    window.onresize = () => {
      //屏幕尺寸变化就重新赋值
      return (() => {
        this.screenWidth = document.body.clientWidth
      })()
    }
  },
  computed: {
    editorHeight() {
      return window.screen.availHeight - 280 + 'px'
    }
  },

  // 方法
  methods: {
    // 消息提示
    info(desc) {
      this.$Notice.info({
        title: '注意!',
        desc
      })
    },
    // 跳转到标题
    roll_to_title(id, e) {
      if (e) {
        e.stopPropagation()
      }

      this.editorRef.scrollToElem(id)
    },

    clik_showcatalog() {
      this.Collapsed_catalog = !this.Collapsed_catalog

      if (this.Collapsed_catalog) {
        this.padding_right = '0px'
        this.Sider_padding = '0px'
      } else if (!this.Collapsed_catalog && this.screenWidth >= break_width) {
        this.padding_right = '180px'
        this.Sider_padding = '5px'
      } else if (!this.Collapsed_catalog && this.screenWidth < break_width) {
        this.padding_right = '0px'
        this.Sider_padding = '5px'
      }
    },
    // 提交数据
    submit() {
      // 条件判断
      if (this.chooseDir_node == null) return this.info('请选择文件夹')
      if (this.formTop.title.length == 0) return this.info('请填写标题')
      if (this.formTop.permission.length == 0) return this.info('请选择权限')
      if (this.formTop.Permission_sensitive.length == 0)
        return this.info('请选择权限')

      // 准备文章数据
      //  新建文章模式与编辑文章模式
      var release_time = ''
      var update_time = ''
      var bucket_filepath = ''
      if (this.useModel == 'new') {
        var id = getUuid()
        bucket_filepath = this.PATH_Article_editor_data + id

        release_time = getNowTime()
      } else {
        bucket_filepath = this.needEdit_nodeData.upload.bucket_filepath

        release_time = this.needEdit_nodeData.upload.release_time
        update_time = getNowTime()
      }

      var article = {
        editor_data: this.editorRef.getHtml()
      }

      // 把文章数据保存到阿里云oss
      // 已经开启同名覆盖,编辑好的文章数据提交后会进行覆盖
      putBuffer('put', bucket_filepath, article).then(({ res, ok, err }) => {
        if (ok) {
          this.$Notice.success({ desc: '文章单独保存成功' })
          // 准备文章节点数据
          var node = {
            title: this.formTop.title,
            mynodeKey: getUuid(),
            node_type: nodeType_article,
            father_nodeKey: this.chooseDir_node.mynodeKey,
            render: this.art_render,

            upload: {
              bucket_filepath,
              explain: this.formTop.explain,
              release_time,
              update_time,
              permission: this.formTop.permission,
              Permission_sensitive: this.formTop.Permission_sensitive
            }
          }

          // 把数据添加到父节点 children 属性上
          var children = this.chooseDir_node.children || []
          children.push(node)
          this.chooseDir_node.children = children
          this.datadir.forEach((item) => {
            if (item.mynodeKey == this.chooseDir_node.mynodeKey) {
              item.children = children
              debugger
            }
          })

          // 把目录树数据data保存到阿里云oss
          putBuffer('put', this.PATH_Directory_tree, this.datadir).then(
            ({ res, ok, err }) => {
              if (ok) {
                this.$Notice.success({ desc: '目录树保存成功' })
                console.log('文章编辑器--保存了目录树')
                // 后续处理
                this.modal1 = false
                this.editorRef.clear()
                this.chooseDir_node = null
                this.formTop.title = ''
                this.formTop.dir = ''
                this.formTop.explain = ''
              } else {
                this.$Notice.error({
                  desc:
                    '目录树数据保存到阿里云oss失败,可能造成编辑器数据泄漏:' +
                    err
                })
              }
            }
          )
        } else {
          this.$Notice.error({ desc: '编辑器数据保存失败:' + err })
        }
      })
    },

    // 获取目录树数据
    getDirTreeData(fun_back) {
      putBuffer('get', this.PATH_Directory_tree).then(({ ok, res, err }) => {
        if (ok) {
          if (res) {
            if (Array.isArray(res)) {
              this.datadir = res
              if (fun_back) {
                fun_back()
              }
              // 设置节点样式
              this.Recursive_directory_tree(this.datadir)
            } else {
              this.$Notice.info('数据非数组')
            }
          }
        } else {
          this.$Notice.error({ desc: '获取目录树数据失败:' + err })
        }
      })
    },

    //递归目录树数据,设置不同样式
    Recursive_directory_tree(dirData) {
      for (let index = 0; index < dirData.length; index++) {
        const element = dirData[index]
        // 设置根文章节点样式
        if (element.node_type && element.node_type == nodeType_article) {
          element['render'] = this.art_render
        }
        // pdf
        if (element.node_type && element.node_type == nodeType_pdf) {
          element['render'] = (h, { root, node, data }) => {
            return h(
              'span',
              {
                style: {
                  display: 'inline-block',
                  width: '100%'
                }
              },
              [
                h('span', [
                  h(resolveComponent('Icon'), {
                    type: 'ios-leaf-outline',
                    style: {
                      marginRight: '8px'
                    }
                  }),
                  h('span', data.title)
                ])
              ]
            )
          }
        }
        // 文件夹样式
        if (
          element.node_type &&
          (element.node_type == nodeType_root_node ||
            element.node_type == nodeType_children_node)
        ) {
          element['render'] = (h, { root, node, data }) => {
            return h(
              'span',
              {
                style: {
                  display: 'inline-block',
                  width: '100%'
                }
              },
              [
                h('span', [
                  h(resolveComponent('Icon'), {
                    type: 'md-folder',
                    style: {
                      marginRight: '8px'
                    }
                  }),
                  h('span', data.title)
                ]),
                h(
                  'span',
                  {
                    style: {
                      display: 'inline-block',
                      float: 'right',
                      marginRight: '32px'
                    }
                  },
                  [
                    h(resolveComponent('Button'), {
                      ...this.buttonProps,
                      icon: 'ios-add',
                      style: {
                        marginRight: '8px'
                      },
                      onClick: (e) => {
                        this.chooseDir(data, e)
                      }
                    })
                  ]
                )
              ]
            )
          }
        }

        if (element.children && element.children.length != 0) {
          this.Recursive_directory_tree(element.children)
        }
      }
    },

    // 选择文件夹
    chooseDir(data, e) {
      this.chooseDir_node = data
      this.formTop.dir = data.title
      if (e) e.stopPropagation()
    },

    // 编辑文章
    edit_articley() {
      // 关闭对话框
      this.modal = false
      if (!this.needEdit_nodeData) return

      // 从oss获取 wangEditor 生成的（即 editorRef.getHtml() 返回的） HTML 数据,并加载
      putBuffer('get', this.needEdit_nodeData.upload.bucket_filepath).then(
        ({ res, ok, err }) => {
          if (ok) {
            if (res.editor_data) {
              this.$Notice.success({ desc: '编辑器数据获取成功' })
              // 编辑器数据
              this.editorRef.setHtml(res.editor_data)

              // 标题,权限...
              // 草稿箱中的文章可能没有 一些数据
              this.formTop.title = this.needEdit_nodeData.title
              this.formTop.permission = this.needEdit_nodeData.upload.permission
              this.formTop.Permission_sensitive =
                this.needEdit_nodeData.upload.Permission_sensitive
              this.formTop.explain = this.needEdit_nodeData.upload.explain

              // 文件夹操作
              // 编辑之前目录树数据应该保持最新,编辑过程中不要再更新数据,
              // 获取目录树数据
              this.getDirTreeData(() => {
                // 选择的文件夹
                var key = this.needEdit_nodeData.father_nodeKey
                var fatherDir = find_dirNode(this.datadir, key)
                // console.log(fatherDir)
                if (fatherDir) {
                  // 删除该文章节点在 当前目录树中的位置 提交时再添加 达到从新选择文件夹的效果 ,如果用户不进行提交操作,oss的目录树数据并没有改变

                  var children = fatherDir.children || []
                  var newlist = []
                  for (let index = 0; index < children.length; index++) {
                    const element = children[index]
                    if (element.node_type == nodeType_article) {
                      if (
                        element.mynodeKey != this.needEdit_nodeData.mynodeKey
                      ) {
                        newlist.push(element)
                      }
                    } else {
                      // 文件夹,pdf类型
                      newlist.push(element)
                    }
                  }

                  fatherDir.children = newlist

                  // 显示文件夹到页面上
                  this.chooseDir(fatherDir)
                }
              })
            } else {
              this.$Notice.error({
                desc: '编辑器数据解析失败:无editor_data属性'
              })
            }
          } else {
            this.$Notice.error({ desc: '获取编辑器数据失败:' + err })
          }
        }
      )
    },

    // 保存到草稿箱
    Save_draft_box() {
      // 关闭对话框
      this.modal = false
    }
  },

  // 生命周期
  created() {
    console.log('aticle组件创造')

    eventbus.on('ev_editor', (editor) => {
      this.editorRef = editor
    })

    // 文章目录,获取本文标题h12345
    eventbus.on('get_show_title_list', (list) => {
      if (Array.isArray(list)) {
        // 对标题进行处理
        for (let index = 0; index < list.length; index++) {
          var element = list[index]

          if (element.type == editor_h2) {
            element.text = '' + element.text
          } else if (element.type == editor_h3) {
            element.text = '' + element.text
          } else if (element.type == editor_h4) {
            element.text = '' + element.text
          } else if (element.type == editor_h5) {
            element.text = '' + element.text
          }
        }

        try {
          this.show_title_list = list
        } catch (e) {}
      } else {
        this.$Notice.error({ desc: '文章标题数据非数组' })
      }
    })

    if (this.useModel === 'edit') {
      // 绑定编辑文章事件
      eventbus.on('need_edit', (node_data) => {
        // 引用目录树管理中的 目录树data5中的节点数据
        this.needEdit_nodeData = node_data
        try {
          // 判断当前是否存在未保存的文章
          if (!this.editorRef.isEmpty()) {
            this.modal = true
          } else {
            this.edit_articley()
          }
        } catch (e) {
          this.modal = true
        }
      })
    }
  },

  // 激活该路由组件时调用
  activated() {
    // 文章组件 激活
    console.log('artice组件激活:' + this.useModel)

    // 编辑文章时会自己更新treedata的
    if (this.useModel == 'new') {
      this.getDirTreeData()
    }

    if (this.useModel === 'edit') {
      eventbus.emit('ev_art_active')
    }
  },
  deactivated() {
    // 文章组件 缓存
  }
}
</script>

<style lang="less" scoped>
.margin {
  margin: 10px 10px;
}

.padding {
  padding: 10px 10px;
}

.header1 {
  font-weight: 600;
  margin-left: 10px;
}

.header2 {
  font-weight: 500;
  margin-left: 30px;
}

.header3 {
  font-weight: 400;
  margin-left: 50px;
}

.header4 {
  font-weight: 300;
  margin-left: 70px;
}

.header5 {
  font-weight: 200;
  margin-left: 90px;
}
</style>
